import sys
import time

from PyGtalkRobot import GtalkRobot
from Products.CMFCore.utils import getToolByName
from zope.app.component.hooks import getSite
from ZPublisher.HTTPRequest import HTTPRequest
from ZPublisher.HTTPResponse import HTTPResponse
from ZPublisher.BaseRequest import RequestContainer
import traceback
import transaction

class OwnioBot(GtalkRobot):
    
    #Regular Expression Pattern Tips:
    # I or IGNORECASE <=> (?i)      case insensitive matching
    # L or LOCALE <=> (?L)          make \w, \W, \b, \B dependent on the current locale
    # M or MULTILINE <=> (?m)       matches every new line and not only start/end of the whole string
    # S or DOTALL <=> (?s)          '.' matches ALL chars, including newline
    # U or UNICODE <=> (?u)         Make \w, \W, \b, and \B dependent on the Unicode character properties database.
    # X or VERBOSE <=> (?x)         Ignores whitespace outside character sets
    
    #"command_" is the command prefix, "001" is the priviledge num, "setState" is the method name.
    #This method is used to change the state and status text of the bot.
    # 
    def getRequest(self):
        resp = HTTPResponse(stdout=None)
        env = {
                'SERVER_NAME':'localhost',
                'SERVER_PORT':'8080',
                'REQUEST_METHOD':'GET',
                'HTTP_USER_AGENT':'OWIO-BOT',
                'SESSION': 'OWNIO-BOT',
                'HTTP_ACCEPT_LANGUAGE': 'en',
                'REMOTE_ADDR':'localhost',
                'HTTP_COOKIE':''
                }
        return HTTPRequest(None, env, resp)
        
    def getContext(self, app):
        return app.__of__(RequestContainer(REQUEST = self.getRequest()))
            
    def command_003_postURL(self, user, message, args):
        #the __doc__ of the function is the Regular Expression of this command, if matched, this command method will be called. 
        #The parameter "args" is a list, which will hold the matched string in parenthesis of Regular Expression.
        '''http://[^+]*?'''
        try:
            print 'command_003_postURL', args
            print message
        
            from Zope import DB
            conn = DB.open()
            root = conn.root()
            app  = root['Application']
            ctx = self.getContext(app)
            print ctx, '...'
        
            url = message
            print 'posting', url
        
            shorturl = getToolByName(ctx.Plone, 'portal_shorturl')
            url = shorturl.addLink(url, api=True, REQUEST=self.getRequest())
            print 'shorturl:',url

            self.replyMessage(user, "posted successful: http://own.io/"+url + " or http://my.own.io/links/" + url[0] + "/" + url)
            
            txn = transaction.get()
            txn.commit()
        except:
            traceback.print_exc()

    def command_001_setState(self, user, message, args):
        #the __doc__ of the function is the Regular Expression of this command, if matched, this command method will be called. 
        #The parameter "args" is a list, which will hold the matched string in parenthesis of Regular Expression.
        '''(available|online|on|busy|dnd|away|idle|out|off|xa)( +(.*))?$(?i)'''
        show = args[0]
        status = args[1]
        jid = user.getStripped()

        # Verify if the user is the Administrator of this bot
        if jid == 'hgeldenhuys@gmail.com':
            print jid, " ---> ",self.getResources(jid), self.getShow(jid), self.getStatus(jid)
            self.setState(show, status)
            self.replyMessage(user, "State settings changed！")

    #This method is used to send email for users.
    def command_002_SendEmail(self, user, message, args):
        #email ldmiao@gmail.com hello dmeiao, nice to meet you, bla bla ...
        '''[email|mail|em|m]\s+(.*?@.+?)\s+(.*?),\s*(.*?)(?i)'''
        email_addr = args[0]
        subject = args[1]
        body = args[2]
        #call_send_email_function(email_addr, subject,  body)
        
        self.replyMessage(user, "\nEmail sent to "+ email_addr +" at: "+time.strftime("%Y-%m-%d %a %H:%M:%S", time.gmtime()))
    
    #This method is used to response users.
    def command_100_default(self, user, message, args):
        '''.*?(?s)(?m)'''
        self.replyMessage(user, time.strftime("%Y-%m-%d %a %H:%M:%S", time.gmtime()))

############################################################################################################################
if __name__ == "__main__":
    bot = SampleBot()
    bot.setState('available', "Simple Gtalk Robot")
    bot.start("ownio.bot@gmail.com", "spoon1024")
